package com.ydlclass.core;

import com.ydlclass.exception.YrpcBootstrapException;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.StringJoiner;

@Slf4j
public class URL {

    private String protocol;

    private List<HostAndPort> hostAndPorts;

    /**
     * 解析如下的uri：zookeeper://192.168.0.125:2181,192.168.0.125:2182
     * @param uri
     */
    public URL(String uri) {
        this.hostAndPorts = new ArrayList<>(4);
        if(uri == null || !uri.contains("://")){
            throw new IllegalArgumentException("The uri parameter is invalid.");
        }
        String[] protocolAndHost = uri.split("://");
        if (protocolAndHost.length != 2){
            throw new YrpcBootstrapException("You passed in an illegal url!");
        }

        this.protocol = protocolAndHost[0];
        String[] ipAndPosts = protocolAndHost[1].split(",");
        for (String ipAndPost : ipAndPosts) {
            String[] result = ipAndPost.split(":");
            if(result.length > 1){
                this.hostAndPorts.add(new HostAndPort(result[0],Integer.valueOf(result[1])));
            }
        }


    }

    public URL(String protocol, List<HostAndPort> hostAndPorts) {
        this.protocol = protocol;
        this.hostAndPorts = hostAndPorts;
    }

    public String getProtocol() {
        return protocol;
    }

    public void setProtocol(String protocol) {
        this.protocol = protocol;
    }

    public List<HostAndPort> getHostAndPorts() {
        return hostAndPorts;
    }

    public void setHostAndPorts(List<HostAndPort> hostAndPorts) {
        this.hostAndPorts = hostAndPorts;
    }

    public static class HostAndPort{
        private String ip;
        private int port;

        public String getIp() {
            return ip;
        }

        public HostAndPort(String ip, int port) {
            this.ip = ip;
            this.port = port;
        }

        public void setIp(String ip) {
            this.ip = ip;
        }

        public int getPort() {
            return port;
        }

        public void setPort(int port) {
            this.port = port;
        }

        @Override
        public String toString() {
            return ip+":"+port;
        }
    }

    /**
     * 获得ip和端口的字符串变现形式
     * @return ip和端口的字符串变现形式
     */
    public String getIpAndPortString(){
        StringJoiner stringJoiner = new StringJoiner(",");
        for (HostAndPort hostAndPort : hostAndPorts) {
            stringJoiner.add(hostAndPort.toString());
        }
        return stringJoiner.toString();
    }
}
